import html2canvas from 'html2canvas'
import JsPDF from 'jspdf'

function getObjectURL(file) {
  let url = window.webkitURL.createObjectURL(file);
  if (window.URL !== undefined) {
    url = window.URL.createObjectURL(file);
  } else if (window.webkitURL !== undefined) {
    url = window.webkitURL.createObjectURL(file);
  }
  return url;
}

function dataURLtoFile(dataurl, filename) {
  var arr = dataurl.split(',');
  var mime = arr[0].match(/:(.*?);/)[1];
  var bstr = atob(arr[1]);
  var n = bstr.length;
  var u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  //转换成file对象
  return new File([u8arr], filename, {type: mime});
  //转换成成blob对象
  //return new Blob([u8arr],{type:mime});
}

function html2pdf(element, name) {
  // 导出之前先将滚动条置顶,不然会出现数据不全的现象
  // @ts-ignore
  window.pageYOffset = 0;
  document.documentElement.scrollTop = 0
  document.body.scrollTop = 0

  return new Promise((resolve) => {
    let w = element.clientWidth; //获取屏幕宽度
    let h = element.clientHeight; //获取屏幕高度
    let scale = 1;
    //一页pdf显示html页面生成的canvas高度;
    let canvas = document.createElement("canvas");
    canvas.width = w * scale;
    canvas.height = h * scale;
    canvas.style.width = w * scale + "px";
    canvas.style.height = h * scale + "px";
    // @ts-ignore
    canvas.getContext("2d").scale(scale, scale);
    let opt = {
      dpi: window.devicePixelRatio * 2,
      scale: scale, //添加scale 参数
      canvas: canvas, //自定义canvas
      logging: false,
      width: w, //canvas 宽度
      hieght: h, //canvas 高度
      useCORS: true, //开启跨域
      background: null,
      allowTaint: true
    };

    html2canvas(element, opt)
      .then((canvas) => {
        var contentWidth = canvas.width;
        var contentHeight = canvas.height;
        var pageData = canvas.toDataURL('image/jpeg', 1.0);
        var imgWidth = 555.28;
        var imgHeight = 555.28/contentWidth * contentHeight;
        var pdf = new JsPDF('', 'pt', 'a4');
        pdf.addImage(pageData, 'jpeg', 20, 20, imgWidth, imgHeight);
        pdf.save(name + '.pdf')
      })
  })
}


export default function htmToPdf(el, name) {
  html2pdf(document.getElementById(el), name);
}
